package com.xy.xymall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xy.common.utils.R;
import com.xy.xymall.cart.feign.ProductFeignService;
import com.xy.xymall.cart.interceptor.CartInterceptor;
import com.xy.xymall.cart.service.CartService;
import com.xy.xymall.cart.to.UserInfoTo;
import com.xy.xymall.cart.vo.CartItemVo;
import com.xy.xymall.cart.vo.CartVo;
import com.xy.xymall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author XY
 * @version 1.0
 * @date 2020/10/27 15:58
 * @Description
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService{

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    private final String CART_PREFIX="xymall:cart:";


    /**
     * @param skuId
     * @param num
     * @author XY
     * @date 2020/10/29 14:29
     * @return com.xy.xymall.cart.vo.CartItemVo
     * 将商品添加到购物车
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //从redis中查询是否有该商品
        String result = (String) cartOps.get(skuId.toString());
        //购物车无此商品
        if(StringUtils.isEmpty(result)){
            //添加新商品
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前商品的详细信息
                R info = productFeignService.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //2、商品添加到购物车
                cartItemVo.setCount(num);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setCheck(true);
            }, threadPoolExecutor);

            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                //3、远程查询sku的组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttr(skuSaleAttrValues);
            }, threadPoolExecutor);

            //等待任务执行完成
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();

            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            return cartItemVo;
        }else{
            //购物车已经有该商品,只要修改数量即可
            CartItemVo cartItemVo = JSON.parseObject(result, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    /**
     * @param skuId
     * @author XY
     * @date 2020/10/29 14:30
     * @return com.xy.xymall.cart.vo.CartItemVo
     * 根据skuId获取购物车某一项信息
     */
    @Override
    public CartItemVo getCartItem(String skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId);
        CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
        return cartItemVo;
    }

    /**
     * @author XY
     * @date 2020/10/29 14:42
     * @return com.xy.xymall.cart.vo.CartVo
     * 获取整个购物车
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo=new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //如果临时购物车的数据还没有进行合并
            List<CartItemVo> tempCartItems = getCartItemsByRedisKey(CART_PREFIX + userInfoTo.getUserKey());
            if(tempCartItems!=null&&tempCartItems.size()>0){
                //临时购物车有数据，需要合并
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清除临时购物车信息
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            //获取当前登录用户的购物车
            List<CartItemVo> cartItems = getCartItemsByRedisKey(cartKey);
            cartVo.setItems(cartItems);

        }else{
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //根据cartKey获取购物车的所有购物项，这里没登陆所以获取的是临时购物车的所有
            List<CartItemVo> cartItems = getCartItemsByRedisKey(cartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    /**
     * @param cartKey
     * @author XY
     * @date 2020/10/29 15:12
     * @return void
     * 根据key清空购物车
     */
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * @param skuId
     * @param check
     * @author XY
     * @date 2020/10/29 15:54
     * @return void
     * 勾选框变化时动态更新redis数据
     */
    @Override
    public void checkItem(String skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId,s);
    }

    /**
     * @param skuId
     * @param num
     * @author XY
     * @date 2020/10/29 16:06
     * @return void
     * 动态刷新购物车中商品数量
     */
    @Override
    public void countItem(String skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId,s);
    }

    /**
     * @param skuId
     * @author XY
     * @date 2020/10/29 16:20
     * @return void
     * 删除购物车中的购物项
     */
    @Override
    public void deleteItem(String skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId);
    }

    /**
     * @Author XY
     * @Date 2020-11-29 10:07
     * @Param []
     * @Return java.util.List<com.xy.xymall.cart.vo.CartItemVo>
     * 获取当前用户已选中的购物车列表
     */
    @Override
    public List<CartItemVo> getUserCartItem() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo!=null){
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
            List<CartItemVo> cartItemsByRedisKey = getCartItemsByRedisKey(cartKey);
            //获取所有被选中的购物项
            List<CartItemVo> collect=null;
            if(cartItemsByRedisKey!=null){
                collect = cartItemsByRedisKey.stream()
                        .filter(item -> item.isCheck())
                        .map(item -> {
                            //将从redis中拿到的价格更新为最新价格
                            R r = productFeignService.getPrice(item.getSkuId());
                            String price = (String)r.get("data");
                            item.setPrice(new BigDecimal(price));
                            return item;
                        })
                        .collect(Collectors.toList());
            }
            return collect;
        }else{
            return null;
        }
    }

    /**
     * 获取到我们要操作的购物车
     * @author XY 
     * @date 2020/10/28 15:02 
     * @return org.springframework.data.redis.core.BoundHashOperations<java.lang.String,java.lang.Object,java.lang.Object>
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey="";
        if(userInfoTo.getUserId()!=null){
            cartKey=CART_PREFIX+userInfoTo.getUserId();
        }else{
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * @param cartKey
     * @author XY
     * @date 2020/10/29 14:52
     * @return java.util.List<com.xy.xymall.cart.vo.CartItemVo>
     *从redis中拿到商购物车商品详情
     */
    private List<CartItemVo> getCartItemsByRedisKey(String cartKey){
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if(values!=null&&values.size()>0){
            List<CartItemVo> collect = values.stream().map(obj -> {
                String str=(String)obj;
                CartItemVo cartItemVo = JSONObject.parseObject(str, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


}
